package com.liuzy.beauty;

import java.io.File;

import com.liuzy.util.UrlQueue;
import com.liuzy.util.Util;

/**
 * 
 * @author liuzy
 * @since 2015年10月25日
 */
public abstract class Beauty {
	private String saveDir;
	private String startUrl;
	public UrlQueue grilQueue = new UrlQueue();
	public UrlQueue imageQueue = new UrlQueue();
	public volatile boolean isRun = true;
	public int threadCount = 20;

	public Beauty(String saveDir, String startUrl) {
		this.saveDir = saveDir;
		this.startUrl = startUrl;
	}

	public void start() {
		grilQueue.add(startUrl);
		jpgStart();
		urlStart();
	}

	public void stop() {
		isRun = false;
		grilQueue.clear();
		imageQueue.clear();
	}

	public void urlStart() {
		for (int i = 0; i < threadCount; i++) {
			new Thread(new Runnable() {
				public void run() {
					while (isRun) {
						String url = grilQueue.get();
						try {
							if (url == null)
								Thread.sleep(500);
							else {
								String html = Util.read2html(url);
								if (html != null)
									search(url, html);
							}
						} catch (Exception e) {
							grilQueue.history.remove(url);
						}
					}
				}
			}).start();
		}
	}

	public abstract void search(String url, String html);

	public void jpgStart() {
		for (int i = 0; i < threadCount; i++) {
			new Thread(new Runnable() {
				public void run() {
					while (isRun) {
						String url = imageQueue.get();
						if (url == null) {
							try {
								Thread.sleep(500);
							} catch (Exception e) {
							}
						} else {
							if (!Util.saveImage(url, new File(saveDir + reName(url)))) {
								imageQueue.history.remove(url);
							}
						}
					}
				}
			}).start();
		}
	}

	public abstract String reName(String url);
}
